<template>
  <view>
    <nav-bar page-title="Marketplace"/>
    <view>
      <!-- selected Category -->
      <view class="categories-box" :style="{top: systemInfo.statusBarHeight + 120 + 'rpx'}">
        <scroll-view class="categories" scroll-x :scroll-left="scrollLeft" scroll-with-animation>
          <view
              v-for="(category, index) in categories" :key="index"
              :class="['radio-20 category-btn', selectedCategory === index ? 'active' : '']"
              @click="selectCategory(index)"
          >
            {{ category.name }}
          </view>
        </scroll-view>
      </view>

      <!-- مەھسۇلاتلار تورى -->
      <view class="padding-20 products-grid">
        <view v-for="(product, index) in products" :key="index" @click="goToDetail(product)"
              class="radio-20 product-card">
          <!--          <image :src="product.image" :alt="product.name" mode="aspectFit" class="product-image"/>-->
          <image :src="product.image" :alt="product.name" mode="aspectFill" class="product-image"/>

          <view class="padding-20">
            <view class="text-to margin-bottom-10 product-name">{{ product.name }}</view>
            <view class="text-to margin-bottom-10 description">{{ product.description }}</view>

            <!-- 价格和添加购物车-->
            <view class="flex-between">
              <u-text size="18" color="#ff0000" bold :text="product.price" mode="price"/>

              <view class="flex-center gap-8">
                <view
                    :class="['center padding-10 add-or-remove remove',{ 'slide-in': product.quantity >= 1 }]"
                    @click.stop="decreaseQuantity(index)">
                  <image src="/static/Marketplace/remove.svg" alt="remove" mode="aspectFill" class="icon"/>
                </view>

                <view>{{ product.quantity }}</view>

                <view class="center padding-10 add-or-remove add" @click.stop="addQuantity(index)">
                  <image src="/static/Marketplace/add.svg" alt="add" mode="aspectFill" class="icon"/>
                </view>

              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- سېتىۋېلىش كۆزنىكى -->
      <view class="flex-between checkout-bar" :class="{ 'slide-up': hasItemsInCart }" @click="onShowCartDetails">
        <view class="cart-icon">
          <image src="/static/Marketplace/cart.svg" mode="aspectFit" class="cart-image"/>
          <view class="center  cart-count">{{ totalItems }}</view>
        </view>

        <view class="flex-1 margin-lr-40">
          <u-text size="32" color="#007aff" bold :text="totalPrice" mode="price"/>
        </view>

        <view class="checkout-button" @click="proceedToCheckout">
          سېتىۋېلىش
        </view>
      </view>

      <view :class="['mask', { 'mask-show': showCartDetails }]" @click="closeCartDetails">
        <!-- مال تەپسىلاتى popup -->
        <view :class="['cart-details-popup',{ 'show': showCartDetails }]" @click.stop>
          <view class="flex-between popup-header">
            <view class="center radio-40 close-btn" @click="closeCartDetails">
              <image class="icon" src="/static/globalIcon/close.svg" mode="aspectFit"/>
            </view>
            <text class="header-title">تاللانغان ماللار</text>
          </view>

          <scroll-view scroll-y class="cart-items">
            <view v-for="(product, index) in cartProducts" v-if="product.quantity > 0" :key="index"
                  class="flex-between cart-item">
              <view class="product-info">
                <text class="product-name">{{ product.name }}</text>
                <u-text size="16" color="#999" bold :text="totalPrice" mode="price"/>
              </view>


              <view class="quantity-controls">
                {{ product.price }}{{ product.quantity }}
                <u-text size="16" color="#ff0000" bold :text="product.price * product.quantity" mode="price"/>
                <view class="control-btn" @click="decreaseQuantity(index)">-</view>
                <text class="quantity">{{ product.quantity }}</text>
                <view class="control-btn" @click="addQuantity(index)">+</view>
              </view>
            </view>
          </scroll-view>

          <view class="popup-footer">
            <view class="clear-cart" @tap="clearCart">
              <text>تازلاش</text>
            </view>
          </view>
        </view>
      </view>
      <tab-bar :current="1"/>
    </view>
  </view>
</template>

<script>
import Vue from "vue";
import NavBar from "@/components/nav-bar/nav-bar.vue";
import {mapState} from "vuex";
import TabBar from "@/components/TabBar/TabBar.vue";

export default Vue.extend({
  name: "Marketplace",
  components: {TabBar, NavBar},
  data() {
    return {
      scrollLeft: 0,
      selectedCategory: 0,
      categories: [], // 分类
      products: [], /// 产品
      // cartProducts: [], // 选择的产品

      totalItems: 0,
      totalPrice: 0,
      hasItemsInCart: false,
      showCartDetails: false
    }
  },
  computed: {
    ...mapState(['systemInfo']),
    cartProducts() {
      return this.products.filter(product => product.quantity > 0);
    },
  },
  onLoad(query) {
    this.getCategoryData()
  },
  methods: {
    onShowCartDetails() {
      this.cartProducts = this.products.filter(product => product.quantity > 0);
      this.showCartDetails = true;
    },

    closeCartDetails() {
      this.showCartDetails = false;
    },

    clearCart() {
      this.categories.forEach(product => {
        if (product.quantity) {
          this.$delete(product, 'quantity');
        }
      });
      this.totalItems = 0;
      this.totalPrice = 0;
      this.hasItemsInCart = false;
      this.closeCartDetails();
    },

    // 获取分类
    getCategoryData() {
      // 后期网路请求 (临时写法)
      let data = [
        {id: 1, name: 'پىرىنتېرلار'},
        {id: 2, name: 'سايمانلار'},
        {id: 3, name: 'قەغەزلەر'},
        {id: 4, name: 'سىيالار'}
      ]
      data.unshift({id: 0, name: 'بارلىق'})
      this.categories = data
      this.getProductsData()
    },
    // 获取产品
    getProductsData() {
      console.log("this.products[this.selectedCategory] ", this.categories[this.selectedCategory])
      const {id} = this.categories[this.selectedCategory]
      console.log('getProductsData', id)

      // 后期网路请求 (临时写法)
      let data = [
        {
          id: 1,
          name: 'HP LaserJet پىرىنتېرى',
          price: 2999,
          category_id: 1,
          image: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.ihFJESuXuIiBTDcPGn3wdQHaFj?w=286&h=215&c=7&r=0&o=5&pid=1.7',
          description: 'يۇقىرى سۈپەتلىك لازېرلىق پىرىنتېر'
        }, {
          id: 2,
          name: 'A4 قەغەز بوغچىسى',
          price: 45,
          category_id: 3,
          image: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.Rok3CX7h1o4paQ5lDx7tvgHaHa?w=196&h=197&c=7&r=0&o=5&pid=1.7',
          description: '100 تاللىق A4 ئۆلچەملىك قەغەز'
        }, {
          id: 3,
          name: 'قارا سىيا',
          price: 20,
          category_id: 4,
          image: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.Y2kQAvKVTh7QAZAEUK27ywHaHa?w=191&h=191&c=7&r=0&o=5&pid=1.7',
          description: 'ئەسلى HP سىيا قۇتىسى'
        }, {
          id: 3,
          name: 'قارا سىيا',
          price: 20,
          category_id: 4,
          image: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.Y2kQAvKVTh7QAZAEUK27ywHaHa?w=191&h=191&c=7&r=0&o=5&pid=1.7',
          description: 'ئەسلى HP سىيا قۇتىسى'
        }, {
          id: 3,
          name: 'قارا سىيا',
          price: 20,
          category_id: 4,
          image: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.5khuV-Y_Ql8Mci8dvwqL4AHaHa?w=191&h=191&c=7&r=0&o=5&pid=1.7',
          description: 'ئەسلى HP سىيا قۇتىسى'
        }
      ]

      if (id === 0) {
        this.products = data
      } else {
        this.products = data.filter(item => item.category_id === id)
      }
    },

    // 分类点击时
    selectCategory(index) {
      this.selectedCategory = index
      this.getProductsData()

      // تاللانغان category نىڭ scroll پوزىتسىيەسىنى ھېسابلاش
      const itemWidth = 100; // category item كەڭلىكى
      const screenWidth = uni.getSystemInfoSync().windowWidth;
      const centerPosition = (screenWidth / 2) - (itemWidth / 2);
      this.scrollLeft = index * itemWidth - centerPosition;
    },
    // 当前item点击时
    goToDetail(product) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${product.id}`
      })
    },
    // 添加
    addQuantity(index) {
      let {quantity} = this.products[index];
      if (!quantity) {
        this.$set(this.products[index], 'quantity', 1);
      } else {
        this.products[index].quantity++;
      }
      this.totalItems++;
      this.totalPrice += this.products[index].price;
      if (!this.hasItemsInCart) {
        this.hasItemsInCart = true;
      }
    },
    // 减小
    decreaseQuantity(index) {
      console.log("this.cartProducts[index] -=-=", this.cartProducts[index])
      let product = this.products[index];
      if (product.quantity > 0) {
        this.products[index].quantity--;
        this.totalItems--;
        this.totalPrice -= product.price;
        if (product.quantity === 0) {
          this.$delete(this.products[index], 'quantity');
        }
      }
      if (this.totalItems === 0) {
        this.hasItemsInCart = false;
      }
    },
    // 购买按钮
    proceedToCheckout() {
      // let {products}=this

      // سېتىۋېلىش فونكىسيەسى
      console.log('Proceeding to checkout');
    },
  }
})
</script>

<style lang="scss">
.categories-box {
  position: sticky;
  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);

  .categories {
    white-space: nowrap;
    padding: 20rpx 0;

    .category-btn {
      display: inline-block;
      padding: 20rpx 40rpx;
      margin: 0 15rpx;
      background: #ffffff;
      font-size: 28rpx;
      color: #333;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      &.active {
        background: #007aff;
        color: #fff;
      }
    }
  }
}

.products-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .product-card {
    width: 48%;
    background: #ffffff;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

    .product-image {
      width: 100%;
      height: 200rpx;
      border-radius: 20rpx 20rpx 0 0;
    }

    .product-name {
      font-size: 32rpx;
      font-weight: bold;
    }

    .description {
      color: #666;
    }

    .add-or-remove {
      border-radius: 30rpx;

      .icon {
        width: 30rpx;
        height: 30rpx;
      }
    }

    &.add {
      background: #007aff;
    }

    &.remove {
      background: #ff0000;
      opacity: 0;
      transform: scale(0.8);
      transition: all 0.3s ease;

      &.slide-in {
        opacity: 1;
        transform: scale(1);
      }
    }
  }
}

/** 购物车 */
.checkout-bar {
  position: fixed;
  bottom: -100px;
  left: 0;
  right: 0;
  height: 80px;
  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  padding: 0 20px;
  //box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  transition: bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 999;

  &.slide-up {
    bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  }

  .cart-icon {
    position: relative;

    .cart-image {
      width: 60rpx;
      height: 60rpx;
    }

    .cart-count {
      position: absolute;
      top: -16rpx;
      right: -16rpx;
      background: #ff0000;
      color: white;
      border-radius: 50%;
      min-width: 36rpx;
      height: 36rpx;
      font-size: 24rpx;
    }
  }

  .checkout-button {
    background: #007aff;
    color: white;
    padding: 24rpx 60rpx;
    border-radius: 50rpx;
    font-weight: 500;
  }
}


/** 选择购物的产品*/
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0);
  z-index: 997;
  transition: all 0.3s ease;
  opacity: 0;
  visibility: hidden;
  touch-action: none; /* سىرىلىشنى توسۇش */
  -webkit-overflow-scrolling: none;

  &.mask-show {
    background: rgba(0, 0, 0, 0.5);
    opacity: 1;
    visibility: visible;
  }
}

.cart-details-popup {
  position: fixed;
  bottom: -100vh;
  left: 0;
  right: 0;
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  transition: all 0.3s;
  z-index: 998;

  &.show {
    bottom: 240rpx;
  }

  .popup-header {
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;

    .close-btn {
      background-color: #ffe1e1;
      border-radius: 50%;
      padding: 14rpx;

      .icon {
        width: 30rpx;
        height: 30rpx;
      }
    }

    .header-title {
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .cart-items {
    //height: calc(100% - 180rpx);
    min-height: 20vh;
    max-height: 60vh;
    padding: 20rpx;

    .cart-item {
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      .product-info {
        flex: 1;

        .product-name {
          font-size: 28rpx;
          margin-bottom: 10rpx;
        }
      }

      .quantity-controls {
        display: flex;
        align-items: center;
        gap: 20rpx;

        .control-btn {
          width: 50rpx;
          height: 50rpx;
          border-radius: 25rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f5f5f5;
        }
      }
    }
  }

  .popup-footer {
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1rpx solid #eee;

    .clear-cart {
      padding: 20rpx 60rpx;
      background: #ff0000;
      color: white;
      border-radius: 30rpx;
    }
  }
}
</style>
